package wsp.dailymarket.partners;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import wsp.dailymarket.auth.AuthenticationBean;
import wsp.dailymarket.obj.UserProfileBean;

/**
 * Servlet Filter that will not allow access without being logged in and being a partner.
 * @author Matt
 */
public class PartnerAuthFilter implements Filter {

	public void init(FilterConfig fc) throws ServletException {}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {
		AuthenticationBean authBean = (AuthenticationBean) ((HttpServletRequest) request).getSession().getAttribute("authenticationBean");
		if (authBean == null || authBean.getAuthentication() == null || !authBean.getAuthentication().isAuthorized()) {
			((HttpServletResponse) response).sendRedirect("../login.do"); // Not logged in, so redirect to login page
		} else if (authBean.getUserProfile().getClientType() != UserProfileBean.CLIENT_TYPE_PARTNER) {
			((HttpServletResponse) response).sendRedirect("../partners.do");
		} else {
			fc.doFilter(request, response); // Logged in, so just continue.
		}
	}

	public void destroy() {}

}
